import SMErouter from 'sme-router'; //引入前端路由
// import axios from 'axios'; //引入axios
import request from './util/request';

//引入视图
import advView from '$v/adv';
import loginView from '$v/login';
import adminListView from '$v/adminList';
import advListView from '$v/advList';


//激活路由,并指定路由的挂载位置
const router = new SMErouter("app","html5")

// 因为路由跳转需要使用router对象,所以把router对象设置给window作为属性
window.router = router;

//配置登录页面路由
router.route("/login",(req,res)=>{
    res.render(loginView())
})

//配置广告页面路由
router.route("/adv",(req,res,next)=>{
    next(advView({
        subRoute: res.subRoute(),
        url: req.url
    }))
})

//二级路由配置
router.route("/adv/adminList",(req,res)=>{
    res.render(adminListView())
    //给保存按钮添加点击事件发送ajax请求
    const osaveAdminBtn = document.getElementById('saveAdminBtn');
    osaveAdminBtn.onclick = async function(){
        //拿到用户输入的内容
        const adminNameValue = document.adminForm.adminName.value.trim();
        const passWordValue = document.adminForm.passWord.value.trim();
        const rePpassWordValue = document.adminForm.rePpassWord.value.trim();
        
        //判断输入内容不能为空
        if(!adminNameValue || !passWordValue || !rePpassWordValue){
            return alert("输入的内容不能为空")
        }

        //判断两次输入的密码一致
        if(passWordValue !== rePpassWordValue){
            return alert("两次输入的密码不一致,请重新输入")
        }

        //输入的内容没有问题向后端发送请求
        try{
            const re = await request.post("/addAdmin",{
                adminName: adminNameValue,
                passWord: passWordValue,
                regTime: new Date().toLocaleString(),
            })
            alert(re.data.msg)
        }catch(e){
            alert(e.message)
        }

    }
})

router.route("/adv/advList",(req,res)=>{
    res.render(advListView())
})

